<?php

namespace Crm\Model;

/**
 * UserPermission数据库模型
 *
 * @author SoChishun <14507247@qq.com>
 * @version 1.0
 * @since 1.0.0 <2015-3-23> SoChishun Added.
 */
class PermissionModel extends AppbaseModel {

    /**
     * 数据表名称
     * @var string
     */
    protected $tableName = 'tuser_permission';

    /**
     * 字段定义
     * @var array
     */
    protected $fields = array('id', 'name', 'parent_id', 'code', 'is_menu', 'link_url', 'ordinal', 'create_time', 'site_id', '_pk' => 'id', '_autoinc' => true);

    /**
     * 命名范围
     * @var array
     */
    protected $_scope = array(
        'main_nav' => array(
            'field' => 'id, name, link_url',
            'where' => array('is_menu' => 1)
        )
    );

    /**
     * 是否批量验证
     * @var boolean
     */
    protected $patchValidate = true;

    /**
     * 验证规则
     * @var array
     */
    protected $_validate = array();

    /**
     * 自动填充
     * @var array
     */
    protected $_auto = array();

    /**
     * 获取角色相关的主菜单列表或刷新缓存
     * 注意：更新角色权限的时候必需刷新
     * @param int $role_id 角色编号,默认0=无权限,-1=不限权限
     * @param boolean $refresh 是否强制刷新缓存
     * @return false|array
     * @since 1.0 <2015-3-23> SoChishun Added.
     */
    public function get_main_nav($role_id, $refresh = false) {
        if ($role_id == 0) {
            return false;
        }
        $key = 'Permission/main_nav_' . $role_id;
        if (!$refresh) {
            $rules = S($key);
            if ($rules) {
                return $rules;
            }
        }
        $where_lv0 = '';
        if ($role_id > 0) {
            $permissions = $this->table('tuser_role')->where(array('id' => $role_id))->getField('permission_rule');
            if (!$permissions) {
                return false;
            }
            $where_lv0 = " and id in ($permissions)";
        }

        $list = $this->base_get_tree_list_fn('main_nav', 0, $where_lv0);
        S($key, $list, C('EXPIRE.ROLE_PERMISSION'));
        return $list;
    }

}
